
import uni_request from './uni_request/uni_request.js'
import $cache from './moudle/cache.js'
import $config from '@/config/app.js'
import $go from './moudle/go.js'
import $dialog from './moudle/dialog.js'
const baseURL = $config.base_url;

const request = uni_request({
	baseURL
})

request.interceptors.request.use(async (config, ...args) => { // 请求拦截器
	// ...
	let token = $cache.get('token');
	
	if (!token) { // 如果没得 token
		// await new Promise(resolve => ))
	}else{
		config.header.token = token // 把 token 放在请求头
	}
	
	config.header.channel = $config.channel;
	config.header.version = $config.version;
	//console.log('config.header',config.header)
	return config
})

request.interceptors.response.use(async (response, ...args) => { // 响应拦截器
	// ...
	let res = response.data || {};
	if (res.error && res.error.error_code ) {
		//uni.setStorageSync('token','');
		if (res.error.error_code == '10009' || res.error.error_code =='9999'){
			setTimeout(function() {
				let url = '/pages/user/login';
				let route = $go.location();	
				if (route){
					url = url + (url.indexOf('?')>0?'&':'?')+'jumpUrl='+encodeURIComponent('/'+route)
				}else{
					route = '';
				}
				if (route.indexOf('user/login')<0){//避免重复进入登录页面
					uni.showToast({
						title: '登录信息失效！请重新登录',
						icon: 'none',
						duration: 1500,
						success() {
							uni.reLaunch({
								url: url
							});
									
						}
					});
				}
		
				clearTimeout();
			}, 1000);
			response.success = false;
		}else if (typeof res.error.error_code=='object'){
			$dialog.auto(res.error.error_message).then(()=>{
				$go.page(res.error.error_code);
			});
			response.success = false;
		}else if (String(res.error.error_code).indexOf('.')>=0 || String(res.error.error_code).indexOf('/')>=0){
			$dialog.auto(res.error.error_message).then(()=>{
				$go.page(res.error.error_code);
			});
			response.success = false;
		}
	} 
	//console.log('response',response);
	return response
})

request.onerror = (...args) => {

} // 错误监听

export default request
